import { useWebSocket } from "@vueuse/core";
import { onUnmounted, computed } from "vue";

/**
 * 各环境WS地址
 */
const origin = {
  // dev: "ws://192.168.88.89:12121/ws/stream",
  dev: "wss://test-bdc.btcdana.org/ws/ws/stream", //  抽美金: /bdc/lottery
  devSG: "wss://bdc-sg.btcdana.org/ws/ws/stream", //  新加坡
  test: "wss://test-bdc.btcdana.org/ws/ws/stream",
  prep: "wss://pre-bdc.btcdana.org/ws/ws/stream",
  prod: "wss://bdc.btcdana.org/ws/ws/stream",
};

let getOrigin: any = () => {
  try {
    // 特殊处理: 新加坡服务器
    if (process.client) {
      if (window && window.location.host.includes("bdc-sg")) {
        return origin["devSG"];
      }
    }
    // 
    const env = useRuntimeConfig().public.WEB_NODE_ENV;
    return origin[env as EnvInfo];
  } catch (error) {
    console.error("getOrigin错误:使用", process.env.WEB_NODE_ENV);
    return origin[(process.env.WEB_NODE_ENV || "test") as EnvInfo];
  }
};

// ws环境地址
let wsOrigin: any = "";

export const useSocket = (
  url: string,
  heartbeat: any = false,
  recoveryFailed?: any,
  onConnected?: any,
  onError?: any
) => {
  if (!process.client) {
    return {
      open: () => {},
      close: () => {},
      data: {},
      send: () => {},
      status: "",
      recoveryFailed,
    };
  }
  if (!wsOrigin) wsOrigin = getOrigin();
  // 1. 生成ws地址
  const wsUrl = computed(() => {
    return `${wsOrigin}${url || ""}`;
  });

  // 2. 初始化
  let onDisconnected: any;
  let onMessage: any;
  let autoReconnect: any = false;
  if (typeof recoveryFailed == "function") {
    autoReconnect = {
      retries: 6,
      delay: 5000,
      onFailed() {
        recoveryFailed && recoveryFailed(); // 重连失败回调
      },
    };
  }
  const { open, close, data, send, status } = useWebSocket(wsUrl, {
    // 3.1 重连: 2024.08.13 发现频繁的 open 和 close 会触发重试逻辑,导致建立多个 socket 链接
    autoReconnect: autoReconnect,
    immediate: false, // 是否立即连接
    heartbeat: heartbeat, // 是否发送心跳
    onConnected: onConnected,
    // onDisconnected: onDisconnected,
    onError: onError,
    // onMessage: onMessage,
  });
  // onConnected?: (ws: WebSocket) => void;
  // onDisconnected?: (ws: WebSocket, event: CloseEvent) => void;
  // ?: (ws: WebSocket, event: Event) => void;
  // onMessage?: (ws: WebSocket, event: MessageEvent) => void;

  // 3. 卸载
  onUnmounted(() => {
    // close();
  });

  return {
    open,
    close,
    data,
    send,
    status,
    recoveryFailed,
  };
};
